using System.Xml.Linq;

namespace ICommonLibrary.Xml {

    public class XElementUtil {

        public static bool GetBoolAttribute(XElement elem, string attributeName, bool def) {
            return Util.GetBool(GetStringAttribute(elem, attributeName), def);
        }

        public static bool? GetBoolAttribute(XElement elem, string attributeName, bool? def) {
            return Util.GetBoolNull(GetStringAttribute(elem, attributeName), def);
        }

        public static int GetIntAttribute(XElement elem, string attributeName, int def) {
            return Util.GetInt(GetStringAttribute(elem, attributeName), def);
        }

        public static int? GetIntAttribute(XElement elem, string attributeName) {
            return Util.GetIntNull(GetStringAttribute(elem, attributeName), null);
        }

        public static double GetDoubleAttribute(XElement elem, string attributeName, double def) {
            return Util.GetDouble(GetStringAttribute(elem, attributeName), def);
        }

        public static double? GetDoubleAttribute(XElement elem, string attributeName) {
            return Util.GetDoubleNull(GetStringAttribute(elem, attributeName), null);
        }

        public static string GetStringAttribute(XElement elem, string attributeName) {
            return GetStringAttribute(elem, attributeName, string.Empty);
        }

        public static string GetStringAttribute(XElement elem, string attributeName, string def) {
            XAttribute attribute = elem.Attribute(attributeName);
            if (attribute == null) {
                return def;
            }
            string value = attribute.Value;
            if (value.Length == 0) {
                return value;
            }
            return value.Trim();
        }

        public static string GetText(XElement elem, string textNodeName) {
            return GetText(elem, textNodeName, string.Empty);
        }

        public static string GetText(XElement elem, string textNodeName, string def) {
            XElement textNode = elem.Element(textNodeName);
            if (textNode == null) {
                return def;
            } 
            string value = textNode.Value;
            return value ?? def;
        }


   }
}